package jannex.mapping;

import jannex.label.LabelMap;
import jannex.sql.JxResultSet;
import jannex.sql.JxResultSetMetaData;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
public final class Handlers {

    private Handlers() {
    }

    public static <E> ResultSetHandler<E> first() {
        return resultSet -> (E) resultSet.getObject(1);
    }

    public static ResultSetHandler<Map<String, Object>> map() {
        return forMap(row -> row);
    }

    public static ResultSetHandler<List<Object>> list() {
        return resultSet -> {
            List<Object> objects = new ArrayList<>();
            for (int i = 0; i < objects.size(); i++) {
                objects.add(resultSet.getObject(i + 1));
            }
            return objects;
        };
    }

    public static <E> ResultSetHandler<E> forMap(final MapHandler<E> handler) {
        return resultSet -> {
            JxResultSetMetaData metaData = resultSet.getMetaData();
            LabelMap.Builder<Object> builder = LabelMap.builder(metaData.getColumnCount());
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                builder.put(metaData.getColumnLabel(i), resultSet.getObject(i));
            }
            return handler.handle(builder.build());
        };
    }
}
